package com.aliyun.heiyu.common.util.sm2;

import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.common.util.sm4cbc.SM4EnDecryption;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * 国密对称加密算法--SM4
 * 含 ECB 和 CBC 两种
 * @author henry
 *
 */
public abstract class SM4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final Charset ENCODING = StandardCharsets.UTF_8;

    public static final String ALGORITHM_NAME = "SM4";

    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";

    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    public static final String DEFAULT_KEY = "E5,26,CD,8D,FC,4E,3B,CA,B0,BA,15,F3,C8,22,B6,AE".replaceAll(",", "");

    public static final String DEFAULT_IV ="9446A1C65749AE61FB417D5C67BEDA51";

    public static final byte[] SKEY=ByteUtils.fromHexString(PropertiesUtil.getValue("jdbcConfig.properties", "privateKey")); //ByteUtils.fromHexString(DEFAULT_KEY);
    public static final byte[] IV=ByteUtils.fromHexString(DEFAULT_IV);

    public static String encrypt_CBC(String data){
        try {
            byte[] bytes = SM4EnDecryption.encrypt_Cbc_Padding(SKEY, IV, data.getBytes());
            String s = Util.byteToHex(bytes);
            return s;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decrypt_CBC(String data){
        try {
            byte[] bytes = SM4EnDecryption.decrypt_Cbc_Padding(SKEY, IV, Util.hexToByte(data));
            //String s = Util.byteToHex(bytes);
            String s = Util.byteToString(bytes);
            return s;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    /*ECB加密*/
    public static String encrypt_ECB(String data) throws Exception {
        byte[] res=encryptECBPadding(ByteUtils.fromHexString(data), SKEY);
        return ByteUtils.toHexString(res);
    }

    /*ECB解密*/
    public static String decrypt_ECB(String data) throws Exception {
        byte[] res=decryptECBPadding(ByteUtils.fromHexString(data), SKEY);
        return ByteUtils.toHexString(res);
    }


    /**
     * 生成ECB暗号
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     * @param algorithmName  算法名称
     * @param mode   模式
     * @param key
     * @return
     * @throws Exception
     */
    private static Cipher generateCipherECB(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(mode, new SecretKeySpec(key, ALGORITHM_NAME));
        return cipher;
    }

    /**
     * 生成CBC暗号
     * @param algorithmName
     *            算法名称
     * @param mode
     *            模式
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    private static Cipher generateCipherCBC(String algorithmName, int mode, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(mode, new SecretKeySpec(key, ALGORITHM_NAME), new IvParameterSpec(iv));
        return cipher;
    }

    /**
     * 自动生成密钥
     * @explain
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static String generateKey() {
        try {
            return ByteUtils.toHexString(generateKey(DEFAULT_KEY_SIZE));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @explain
     * @param keySize
     * @return
     * @throws Exception
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * 加密模式之Ecb
     * @explain
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    protected static byte[] encryptECBPadding(byte[] data, byte[] key) throws Exception {
        Cipher cipher = generateCipherECB(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @explain
     * @param key
     * @param encrypted
     * @return
     * @throws Exception
     */
    protected static byte[] decryptECBPadding(byte[] encrypted, byte[] key) throws Exception {
        Cipher cipher = generateCipherECB(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(encrypted);
    }

    /**
     * 加密模式之cbc
     * @explain
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    protected static byte[] encryptCBCPadding(byte[] data, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = generateCipherCBC(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     * @explain
     * @param key
     * @param encrypted
     * @return
     * @throws Exception
     */
    protected static byte[] decryptCBCPadding(byte[] encrypted, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = generateCipherCBC(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
        return cipher.doFinal(encrypted);
    }

    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密字符串
     *            16进制密钥
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(String source) {
        return encrypt(source, DEFAULT_KEY);
    }


    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密数据
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(byte[] source) {
        return encrypt(source, DEFAULT_KEY);
    }

    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(String source, String hexKey) {
        return encrypt(source.getBytes(ENCODING), hexKey);
    }

    /**
     * 加密
     * @explain 加密模式：ECB
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(byte[] source, String hexKey) {
        byte[] cipherArray;
        try {
            cipherArray = encryptECBPadding(source, ByteUtils.fromHexString(hexKey));
            return ByteUtils.toHexString(cipherArray);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static byte[] decrypt(String encrypted) {
        return decrypt(encrypted, DEFAULT_KEY);
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToString(String encrypted) {
        return decryptToString(encrypted, DEFAULT_KEY);
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToHex(String encrypted, String hexKey) {
        byte[] data = decrypt(encrypted, hexKey);
        return ByteUtils.toHexString(data);
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToString(String encrypted, String hexKey) {
        return new String(decrypt(encrypted, hexKey), ENCODING);
    }

    /**
     * 解密
     * @explain 解密模式：采用ECB
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(String encrypted, String hexKey) {
        try {
            return decryptECBPadding(ByteUtils.fromHexString(encrypted), ByteUtils.fromHexString(hexKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encrypted.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 加密
     * @explain 加密模式：CBC
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(String source, String hexKey, String iv) {
        return encrypt(source.getBytes(ENCODING), hexKey, iv);
    }

    /**
     * 加密
     * @explain 加密模式：CBC
     * @param source
     *            待加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encrypt(byte[] source, String hexKey, String iv) {
        byte[] cipherArray;
        try {
            cipherArray = encryptCBCPadding(
                source
                ,ByteUtils.fromHexString(hexKey)
                , ByteUtils.fromHexString(iv));
            return ByteUtils.toHexString(cipherArray);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据加密失败", e);
        }
    }

    /**
     * 解密
     * @explain 解密模式：采用CBC
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptToString(String encrypted, String hexKey, String iv) {
        return new String(decrypt(encrypted, hexKey, iv), ENCODING);
    }

    public static String decryptCBCToString(String encrypted) {
        return new String(decrypt(encrypted, ByteUtils.toHexString(SKEY), DEFAULT_IV), ENCODING);
    }

    /**
     * 解密
     * @explain 解密模式：采用CBC
     * @param encrypted
     *            16进制的加密字符串
     * @param hexKey
     *            16进制密钥
     * @param iv
     *            16进制偏移量
     * @return 解密后的字符串
     * @throws Exception
     */
    public static byte[] decrypt(String encrypted, String hexKey, String iv) {
        try {
            if (StringUtils.isBlank(encrypted)) {
                return new byte[] {};
            }

            return decryptCBCPadding(
                ByteUtils.fromHexString(encrypted)
                ,ByteUtils.fromHexString(hexKey)
                , ByteUtils.fromHexString(iv));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encrypted.getBytes(StandardCharsets.UTF_8);
    }
}
